package encaps.utils.rendering;

import encaps.resources.Response;
import encaps.utils.ImageServlet;
import static encaps.utils.html.HTML.*;
import encaps.utils.html.HTMLElement;
import encaps.utils.html.HTMLElementSequence;
import org.jdom.Element;

public class ImageFactory implements FieldFactory {

    public static final String ALT_IMG_TEXT = "image";
    public static final String ACCEPTED_TYPES = "image/*";

    @Override
    public HTMLElement renderField(Element e, boolean edit) {
        HTMLElementSequence result = new HTMLElementSequence();
        String value = e.getChildTextTrim(Response.VALUE);

        HTMLElement image = new HTMLElement(IMG);
        image.addAttribute(SRC, String.format("%s?%s=%s",
                ImageServlet.IMAGE_SERVLET_NAME, ImageServlet.PATH, value));
        image.addAttribute(ALT, ALT_IMG_TEXT);
        result.addContent(image);
        result.addContent(HTMLElement.createBr());

        if (edit) {
            String key = e.getChildTextTrim(Response.KEY);
            HTMLElement fileInput = new HTMLElement(INPUT);
            fileInput.addAttribute(TYPE, FILE);
            fileInput.addAttribute(ACCEPT, ACCEPTED_TYPES);
            fileInput.addAttribute(SIZE, DEFAULT_INPUT_SIZE);
            fileInput.addAttribute(NAME, key);

            result.addContent(fileInput);
            result.addContent(HTMLElement.createBr());
        }

        return result;
    }
}
